package user

import (
	"context"
	"fmt"
	"gitee.com/binny_w/gin_starter/core"
	"gitee.com/binny_w/go-util"
	util2 "gitee.com/binny_w/go-util/v2"
	"time"
)

func InitAdmin(ctx context.Context, name, pass string) error {
	var err error
	pass, err = util.StrHashPass(pass)
	if err != nil {
		return err
	}
	var newId int64
	newId, err = MdlUser.Table.Insert(ctx, &util2.MysqlRow{
		"name":       name,
		"role":       core.Rbac.SuperAdmin,
		"pasd":       pass,
		"created_at": time.Now().Unix(),
	})
	if err != nil {
		return err
	}
	if newId == 0 {
		return fmt.Errorf("newId is zero")
	}
	var bln bool
	bln, err = core.Rbac.AddRolesForUser(fmt.Sprintf("user:%d", newId), core.Rbac.SuperAdmin)
	if err != nil {
		return err
	}
	if !bln {
		return fmt.Errorf("add role [super admin] for user:%d failed", newId)
	}
	return nil
}
